const express = require('express')
const Router = express.Router()
const query = require('./db')
const path = require('path')
const multer = require('multer')


// 设置上传文件的配置
let storage = multer.diskStorage({
    // 上传文件保存目录，无则自动创建
    // 要放到后端的static文件夹中
    destination: path.join(__dirname, '../static/images/avatar'),
    // 格式化文件名与后缀名
    filename: (req, file, cb) => {
        // req请求对象
        // file 文件
        // cb 回调函数，用于确认文件名
        // file.originalname 上传的原文件的名称加上后缀的
        // file.fieldname formdata数据中存放文件的属性 avatar
        let ext = path.extname(file.originalname)
        cb(null, file.fieldname + '-' + Date.now() + ext);
    }
})
// 使用配置
let upload = multer({ storage })



module.exports = Router

// 获取用户信息
Router.get('/getUserInfo', async (req, res) => {
    try {
        let { user_id } = req.query
        let data = await query(`select * from user where user_id=${user_id}`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: '用户不存在'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取用户信息成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


// 获取个人用户的所有文章
Router.get('/getUserArticle', async (req, res) => {
    try {
        let { user_id } = req.query
        let data = await query(`select * from article where article_author_id=${user_id} order by article_time desc`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: '当前用户没有文章'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取个人用户文章成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


/**
 * 上传头像
 */
Router.post('/updateAvatar', upload.single("file"), async (req, res) => {
    try {
        let file = req.file
        let { user_id } = req.body
        let imgurl = `${process.env.BASE_URL}/images/avatar/` + file.filename;
        let data = await query(`update user set user_avatar='${imgurl}' where user_id=${user_id}`)
        res.send({
            code: 200,
            msg: '上传头像成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 文字型用户信息失去焦点后更新数据库
 */
Router.post('/updateUserText', async (req, res) => {
    try {
        let { user_id, text, type } = req.body
        let data = await query(`update user set ${type}='${text}' where user_id=${user_id}`)
        res.send({
            code: 200,
            msg: "修改用户信息成功",
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

// 查找用户
Router.get('/searchUser', async (req, res) => {
    try {
        let { searchUserValue } = req.query
        let userData = await query(`select * from user where user_name like '%${searchUserValue}%'`)
        // userData.forEach(async (item) => {
        //     let articleData = await query(`select * from article where article_author_id=${item.user_id}`)
        //     item.article = articleData
        // })
        if (userData.length === 0) {
            res.send({
                code: 400,
                msg: '没有查询到该用户'
            })
            return
        }

        for (const item of userData) {
            let articleData = await query(`select * from article where article_author_id=${item.user_id} order by article_time desc limit 5`)
            let followData = await query(`select count(*) as followCount from follow where follow_id='${item.user_id}'`)
            let fansData = await query(`select count(*) as fansCount from follow where fans_id='${item.user_id}'`)
            item.article = articleData
            item.follow = followData[0].followCount
            item.fans = fansData[0].fansCount
        }

        userData.forEach(item => {
            item.count = item.article.reduce((sum, i) => {
                return sum += i.article_like * 1 + i.article_collect * 1
            }, 0)
        });

        res.send({
            code: 200,
            msg: '查询用户成功',
            userData
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})